let containerDiv = document.querySelector('.container');
let inputs = document.querySelectorAll('input');
let button = document.querySelector('#submit');
let revertButton = document.querySelector('#revert');
button.onclick = function() {
    let from = inputs[0].value;
    let to = inputs[1].value;
    let message = inputs[2].value;
    if(from == '' || to == '' || message == ''){
        return;
    }
    let rowDiv = document.createElement('div');
    rowDiv.className = 'row message';
    rowDiv.innerHTML = from + '对' + to + '说' + message;
    containerDiv.appendChild(rowDiv);
    for(let input of inputs){
        input.value = '';
    }

    // 给服务器发送post请求，把上述数据提交到服务器
    let body = {
        "from":from,
        "to":to,
        "message":message
    };
    let strBody = JSON.stringify(body);
    console.log(strBody);
    $.ajax({
        type:"post",
        url:"Message",
        data:strBody,
        contentType:"application/json;charset=utf8",
        success:function (body){
            console.log("数据发布成功");
        }
    });
}

revertButton.onclick = function(){
    let rows = document.querySelectorAll('.message');
    if(rows.length == 0){
        return;
    }
    containerDiv.removeChild(rows[rows.length-1]);
    $.ajax({
        type: "delete",
        url: "Message",
        success:function(body){
            console.log("数据删除成功");
        }
    });
}

//页面加载，发送GET请求，从服务器中获取数据
$.ajax({
    type: "get",
    url: "Message",
    success: function(body){
        let containerDiv = document.querySelector('.container');
        //此时的body就是js对象的数组，本来服务器返回的是一个json格式的字符串，
        //但是jQuery的ajax能够自动识别并将其转换成json字符串转为js对象数组
        for(let message of body){
            //针对每个message构造一个div
            let rowDiv = document.createElement('div');
            rowDiv.className = 'row message';
            rowDiv.innerHTML = message.from + '对' + message.to + '说' + message.message;
            containerDiv.appendChild(rowDiv);
        }
    }
});